import React, { useState, useEffect } from 'react';
import {
  Elements,
  PaymentElement,
  useStripe,
  useElements
} from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { paymentService } from '../services/payment';
import { CreditPackage } from '../services/credits';

// Stripe公钥 - 从后端获取
let stripePromise: Promise<any> | null = null;

const getStripe = async () => {
  if (!stripePromise) {
    try {
      const config = await paymentService.getStripeConfig();
      stripePromise = loadStripe(config.data.publishableKey);
    } catch (error) {
      console.error('Failed to load Stripe config:', error);
      throw error;
    }
  }
  return stripePromise;
};

interface PaymentFormProps {
  creditPackage: CreditPackage;
  userId: string;
  onSuccess: (paymentIntent: any) => void;
  onError: (error: string) => void;
  onCancel: () => void;
  clientSecret: string;
}

const PaymentForm: React.FC<PaymentFormProps> = ({
  creditPackage,
  userId,
  onSuccess,
  onError,
  onCancel,
  clientSecret
}) => {
  const stripe = useStripe();
  const elements = useElements();
  const [isProcessing, setIsProcessing] = useState(false);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();

    if (!stripe || !elements || !clientSecret) {
      return;
    }

    setIsProcessing(true);

    try {
      // 使用confirmPayment替代confirmCardPayment，适用于PaymentElement
      const { error, paymentIntent } = await stripe.confirmPayment({
        elements,
        confirmParams: {
          return_url: window.location.origin + '/payment-success', // 可选：支付成功后的重定向URL
        },
        redirect: 'if_required'
      });

      if (error) {
        onError(error.message || 'Payment failed');
      } else if (paymentIntent?.status === 'succeeded') {
        onSuccess(paymentIntent);
      }
    } catch (error: any) {
      onError(error.message || 'Payment processing failed');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="bg-gray-50 p-6 rounded-lg">
        <h3 className="text-lg font-medium text-gray-900 mb-4">Choose Payment Method</h3>
        <div className="mb-4">
          <PaymentElement 
            id="payment-element" 
            options={{
              layout: "tabs",
              defaultValues: {
                billingDetails: {
                  name: '',
                  email: '',
                }
              }
            }}
          />
        </div>
      </div>

      <div className="bg-blue-50 p-4 rounded-lg">
        <div className="flex justify-between items-center">
          <span className="font-medium text-gray-900">Total:</span>
          <span className="text-xl font-bold text-blue-600">${creditPackage.price}</span>
        </div>
        <div className="text-sm text-gray-600 mt-1">
          {creditPackage.credits} credits • Valid for {creditPackage.validDays} days
        </div>
      </div>

      <div className="flex space-x-4">
        <button
          type="button"
          onClick={onCancel}
          className="flex-1 py-3 px-4 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50 transition-colors"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={!stripe || isProcessing || !clientSecret}
          className="flex-1 py-3 px-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          {isProcessing ? (
            <div className="flex items-center justify-center">
              <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              Processing...
            </div>
          ) : (
            `Pay $${creditPackage.price}`
          )}
        </button>
      </div>
    </form>
  );
};

interface StripePaymentProps {
  creditPackage: CreditPackage;
  userId: string;
  onSuccess: (paymentIntent: any) => void;
  onError: (error: string) => void;
  onCancel: () => void;
}

// 定义Appearance API配置
const appearance = {
  theme: 'stripe' as 'stripe' | 'night' | 'flat', // 基础主题：'stripe', 'night', 'flat'
  variables: {
    colorPrimary: '#0570de', // 主色调
    colorBackground: '#ffffff', // 背景色
    colorText: '#30313d', // 文本颜色
    colorDanger: '#df1b41', // 错误状态颜色
    fontFamily: '"Helvetica Neue", Helvetica, sans-serif', // 字体
    spacingUnit: '4px', // 间距单位
    borderRadius: '8px', // 边框圆角
  },
  rules: {
    '.Label': {
      marginBottom: '8px',
      fontWeight: '600',
    },
    '.Input': {
      padding: '12px',
      borderColor: '#E0E6EB',
      boxShadow: '0px 1px 1px rgba(0, 0, 0, 0.03)',
      fontSize: '16px',
    },
    '.Input:focus': {
      borderColor: 'var(--colorPrimary)',
      boxShadow: '0 0 0 1px var(--colorPrimary)',
    },
    '.Error': {
      marginTop: '8px',
      fontSize: '14px',
    },
    '.Tab': {
      padding: '10px 16px',
      borderRadius: '8px',
      border: '1px solid #E0E6EB',
    },
    '.Tab:hover': {
      backgroundColor: '#F7FAFC',
    },
    '.Tab--selected': {
      borderColor: 'var(--colorPrimary)',
      backgroundColor: '#F0F9FF',
    },
    '.TabLabel': {
      fontWeight: '500',
    },
    '.TabIcon': {
      marginRight: '8px',
    },
  }
};

const StripePayment: React.FC<StripePaymentProps> = (props) => {
  const [stripePromise, setStripePromise] = useState<Promise<any> | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');
  const [clientSecret, setClientSecret] = useState<string>('');

  // 获取Stripe实例和客户端密钥
  useEffect(() => {
    const initStripe = async () => {
      try {
        const stripe = await getStripe();
        setStripePromise(Promise.resolve(stripe));
        
        // 创建支付意图获取客户端密钥 - 启用所有支付方式
        const response = await paymentService.createPaymentIntent(props.userId, {
          amount: Math.round(props.creditPackage.price * 100),
          currency: 'usd',
          description: `Purchase ${props.creditPackage.name} credit package`,
          metadata: {
            packageId: props.creditPackage.id,
            credits: props.creditPackage.credits.toString(),
            validDays: props.creditPackage.validDays.toString()
          },
          automaticPaymentMethods: true,
          allowRedirects: true
        });
        
        setClientSecret(response.data.clientSecret);
      } catch (error: any) {
        setError(error.message || 'Failed to initialize Stripe');
      } finally {
        setLoading(false);
      }
    };

    initStripe();
  }, [props.creditPackage, props.userId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span className="ml-2 text-gray-600">Loading payment form...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg">
        <p className="font-medium">Payment initialization failed</p>
        <p className="text-sm">{error}</p>
        <button
          onClick={props.onCancel}
          className="mt-2 text-blue-600 hover:text-blue-800 font-medium"
        >
          Go back
        </button>
      </div>
    );
  }

  if (!clientSecret) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span className="ml-2 text-gray-600">Preparing payment...</span>
      </div>
    );
  }

  return (
    <Elements 
      stripe={stripePromise} 
      options={{
        clientSecret,
        appearance,
        loader: 'auto'
      }}
    >
      <PaymentForm {...props} clientSecret={clientSecret} />
    </Elements>
  );
};

export default StripePayment;